package com.example.common.exception;

import com.example.common.model.ResultObj;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.exceptions.PersistenceException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLSyntaxErrorException;

/**
 * @Author: lex
 * @Date: 2018/11/14
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public ResultObj NullPointerExceptionHandler(HttpServletRequest request, NullPointerException exception) throws Exception {
        log.error("空指针异常", exception);
        return new ResultObj(407,"空指针异常"+exception.getMessage());
    }

    @ExceptionHandler(SQLSyntaxErrorException.class)
    @ResponseBody
    public ResultObj SQLSyntaxErrorExceptionHandler(HttpServletRequest request, SQLSyntaxErrorException exception) throws Exception {
        log.error("sql语句出错", exception);
        return new ResultObj(407,"sql语句出错");
    }
    @ExceptionHandler(PersistenceException.class)
    @ResponseBody
    public ResultObj PersistenceExceptionHandler(HttpServletRequest request, PersistenceException exception) throws Exception {
        log.error("数据库字段数据类型有误", exception);
        return new ResultObj(407,"数据库字段数据类型有误");
    }
    @ExceptionHandler(BadSqlGrammarException.class)
    @ResponseBody
    public ResultObj BadSqlGrammarExceptionHandler(HttpServletRequest request, BadSqlGrammarException exception) throws Exception {
        log.error("sql建表错误", exception);
        return new ResultObj(407,"sql建表错误");
    }

    @ExceptionHandler(ArrayIndexOutOfBoundsException.class)
    @ResponseBody
    public ResultObj ArrayIndexOutOfBoundsExceptionHandler(HttpServletRequest request, ArrayIndexOutOfBoundsException exception) throws Exception {
        log.error("数组索引异常", exception);
        return new ResultObj(407,"数组索引异常");
    }

    //@ExceptionHandler(UnauthorizedException.class)
    //@ResponseBody
    //public ResultObj UnauthorizedExceptionExceptionHandler(HttpServletRequest request, UnauthorizedException exception) throws Exception {
    //    log.error("shiro权限不足", exception);
    //    return new ResultObj(407,"shiro权限不足");
    //}

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResultObj exceptionHandler(HttpServletRequest request, Exception exception) throws Exception {
        log.error("服务器繁忙", exception);
        return new ResultObj(407,"服务器繁忙");
    }

}
